import time
import plugin
import config

import os
import sys
import util

from threading import Thread
import multiprocessing
from multiprocessing import Process
import rmi


class NameServer(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.starter = rmi.RMINameServer()

    def run(self):
        print "Starting name server..."
        self.starter.start()

    def waitUntilStarted(self):
        return self.starter.waitUntilStarted()

class ServiceConnector(rmi.RMIObject):
    def __init__(self, server_pid):
        rmi.RMIObject.__init__(self)
        self.server_pid = server_pid

    def connect(self, service, service_url):
        self.register_service(service, service_url)

    def stop(self):
        print "about to kill server"
        os.kill(self.server_pid, 9)
        self.server.shutdown(True)

class Server(Thread,rmi.RMIServer):
    def __init__(self):
        Thread.__init__(self)
        rmi.RMIServer.__init__(self)
        self.setDaemon(1)
        self.ready = 0

    def run(self):
        self.services = ServiceConnector(os.getpid())
        self.connect(self.services, 'services')
        print "ABOUT TO START SERVICES DAEMON"
        self.ready = 1
      
        try:
            self.requestLoop()
        except Exception , e:
            print str(e)
        finally:
            self.shutdown(True)


def start_name_server():
    rmi.config()
    ns = NameServer()
    ns.start()
    ns.waitUntilStarted()

def startServer():
    start_name_server()
    server = Server()
    server.start()
    while not server.ready:
        time.sleep(1)
    print "RPC Server Started..."
    return server

def service(service_name):
    return rmi.RMIService.service(service_name)

def register_service(service_name, service_instance):
    rmi.RMIService.register_service(service_name, service_instance)


START = 1
STOP = 2
QUIT = 3

class ServiceInterface(rmi.RMIObject):
    def __init__(self):
        rmi.RMIObject.__init__(self)

    def describe(self, service):
        pass

    def services(self):
        pass

    def stop(self):
        pass


class Service(Process):
    def __init__(self, path, plugin_name):
        Process.__init__(self, name = plugin_name)
        
        self.path = path
        self.name = plugin_name

        self.request_queue = multiprocessing.Queue()
        self.result_queue = multiprocessing.Queue()

        self.handlers = {}
 
        self.register_handler(QUIT,self.quit)

    def register_handler(self,key,handler):
        self.handlers[key] = handler

    def post(self,data):
        self.request_queue.put(data)

    def run(self):
        print "About to start plugin ",self.path

        while True:
            ''' this is a blocking get call so it should be ok, no sleep required '''
            (command,args) = self.request_queue.get()
            if command == QUIT:
                self.quit(args)
                break
            self.process(command,args)
        print "plugin {0} killed".format(self.name)

    def process(self,command,args):
        if self.handlers.has_key(command) == False:
            return
        self.handlers[command](args)

    def stop(self,args=None):
        self.post((QUIT,args))

    def quit(self,args=None):
        print "QUITING {0}".format(self.path)



    
    
                                       

                                   


